import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns

# 设置随机种子保证重复性
np.random.seed(42)

# 生成虚拟数据集
data_size = 200
df = pd.DataFrame({
    'Feature_1': np.random.normal(loc=50, scale=10, size=data_size),
    'Feature_2': np.random.normal(loc=30, scale=5, size=data_size),
    'Feature_3': np.random.normal(loc=60, scale=15, size=data_size)
})

# 随机插入缺失值
missing_rate = 0.2
for col in df.columns:
    df.loc[df.sample(frac=missing_rate).index, col] = np.nan

# 绘制缺失值前的分布
fig, axes = plt.subplots(2, 2, figsize=(12, 10))
fig.suptitle("Data Imputation Analysis with Median Filling", fontsize=16, fontweight='bold')

# 缺失值情况可视化
sns.heatmap(df.isnull(), cbar=False, cmap='viridis', ax=axes[0, 0])
axes[0, 0].set_title("Missing Values Before Imputation", fontsize=14)

# 应用中位数填补
df_filled = df.fillna(df.median())

# 缺失值填补后的情况可视化
sns.heatmap(df_filled.isnull(), cbar=False, cmap='viridis', ax=axes[0, 1])
axes[0, 1].set_title("Missing Values After Median Imputation", fontsize=14)

# 绘制填补前后的分布对比
for idx, col in enumerate(df.columns):
    sns.histplot(df[col], color='red', alpha=0.5, kde=True, ax=axes[1, idx % 2], label='Before Imputation')
    sns.histplot(df_filled[col], color='blue', alpha=0.5, kde=True, ax=axes[1, idx % 2], label='After Imputation')
    axes[1, idx % 2].set_title(f"{col} Distribution Before and After Imputation", fontsize=14)
    axes[1, idx % 2].legend()

plt.tight_layout(rect=[0, 0, 1, 0.96])
plt.show()